﻿package com.urbansquall.echo
{
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IEventDispatcher;
	import flash.media.SoundChannel;
	import flash.media.SoundTransform;
	
	/**
	 * Wraps a SoundChannel to automatically manage "Group" and "Local" volume.
	 * @author Marshall Powers
	 */
	public class ChannelWrapper extends EventDispatcher
	{
		private var m_volume : Number;
		private var m_parent : SoundGroup;
		private var m_channel : SoundChannel;
		
		public function ChannelWrapper(a_channel : SoundChannel) 
		{
			m_channel = a_channel;
			m_volume = 1.0;
			m_channel.addEventListener(Event.SOUND_COMPLETE, completeEvent);
		}
	
		//public function get parent() : SoundGroup
		//{
		//	return m_parent;
		//}
		
		public function set parent(a_group : SoundGroup) : void
		{
			m_parent = a_group;
		}
		
		private function completeEvent(a_event : Event) : void
		{
			this.dispatchEvent(new WrapperEvent(this, WrapperEvent.SOUND_COMPLETE));
		}
	
		public function stop() : void
		{
			m_channel.stop();
			this.dispatchEvent(new WrapperEvent(this, WrapperEvent.SOUND_STOPPED));	
		}
		
		public function get localVolume() : Number
		{
			return m_volume;
		}
		
		public function set localVolume(a_volume : Number) : void
		{
			m_volume = a_volume;
			updateChannelVolume();
		}
		
		public function updateChannelVolume() : void
		{
			var st: SoundTransform = m_channel.soundTransform;
			st.volume = localVolume * m_parent.volume;
			m_channel.soundTransform = st;
		}
		
		/* this function is provided so you can change other properties of the SoundChannel. 
		 * Do not try to control the soundchannel's volume, since ChannelWrapper and SoundGroup may change it on their own.
		 * 
		 * Slso, do not call stop on the SoundChannel instance or you will leak objects in the parent SoundGroup. Instead, call
		 * the stop method of the ChannelWrapper.
		 */
		public function get channel() : SoundChannel
		{
			return m_channel;
		}
	}
}